<template>
  <div class="assistant-aside">
    <el-button type="primary" @click="handleAddAssistant"> 新建助理 </el-button>
    <el-divider />
    <div class="assistant-list">
      <div
        v-for="(item, index) in assistantList"
        :key="index"
        :class="['assistant-item', { active: activeIndex === index }]"
        @mouseover="mouseenter(index)"
        @mouseleave="mouseleave($event, index)"
        @click="handleClickAssistant(item, index)"
      >
        <div class="assistant-info" @click.prevent>
          <el-avatar :src="baseUrl + item?.avatar" :size="30"></el-avatar>
          <div class="name-desc">
            <div class="name">{{ item?.name }}</div>
            <div class="desc">{{ item?.description }}</div>
          </div>
        </div>
        <!-- 更多操作按钮 -->
        <el-dropdown
          v-show="hoverIndex === index"
          ref="dropdownRefs"
          trigger="hover"
          @visible-change="(visible) => handleDropdownVisible(visible, index)"
        >
          <el-icon class="more-actions"><MoreFilled /></el-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click.stop="handleMenu(item, 'edit')">
                <el-icon><Edit /></el-icon>编辑
              </el-dropdown-item>
              <el-dropdown-item
                @click.stop="handleMenu(item, 'delete')"
                divided
              >
                <el-icon><Delete /></el-icon>删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
  <!-- 新建助理弹窗 -->
  <AssistantDialog
    v-model:modelValue="dialogVisible"
    :assistantData="assistantData"
    :addEdit="addEdit"
    @confirm="onConfirm"
  ></AssistantDialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import AssistantDialog from "./components/assistant-dialog.vue";
import { assistantListApi, assistantRemoveApi } from "@/api/knowledge/chat.js";

let assistantList = ref([]);
let assistantData = ref();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const activeIndex = ref(0);
const hoverIndex = ref(-1);
const dialogVisible = ref(false);
const dropdownVisible = ref(false);
const dropdownRefs = ref(null);
const addEdit = ref("add");

const emits = defineEmits(["assistantInfo"]);

onMounted(() => {
  getAssistantList(true);
});

// 获取助理列表
const getAssistantList = async (isInit = false) => {
  const { data } = await assistantListApi();
  assistantList.value = data;
  if (isInit) {
    emits("assistantInfo", data?.[0]);
  }
};

// 删除助理
const deleteAssistant = async (id) => {
  const { code } = await assistantRemoveApi(id);
  if (code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getAssistantList();
  }
};

const handleAddAssistant = () => {
  dialogVisible.value = true;
  addEdit.value = "add";
};

const handleClickAssistant = (item, index) => {
  activeIndex.value = index;
  emits("assistantInfo", item);
};

const handleMenu = (item, type) => {
  if (type === "edit") {
    assistantData.value = item;
    dialogVisible.value = true;
    addEdit.value = "edit";
  }
  if (type === "delete") {
    ElMessageBox.confirm("确定删除吗?", "提示", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning",
    })
      .then(() => {
        deleteAssistant(item.id);
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      });
  }
};

const onConfirm = (val) => {
  console.log(val, "确定----");
  getAssistantList();
};

const mouseenter = (index) => {
  hoverIndex.value = index;
};

const mouseleave = (event, index) => {
  // 如果下拉菜单可见，则不隐藏操作按钮
  if (dropdownVisible.value && hoverIndex.value === index) return;

  // 检查是否移动到了下拉菜单
  const dropdownEl = dropdownRefs.value[index]?.$el;
  if (dropdownEl) {
    const dropdownMenu = dropdownEl.querySelector(".el-dropdown-menu");
    if (dropdownMenu?.contains(event.relatedTarget)) {
      return;
    }
  }

  // 真正离开时才隐藏
  hoverIndex.value = -1;
};

// 处理下拉菜单可见状态变化
const handleDropdownVisible = (visible, index) => {
  dropdownVisible.value = visible;
  if (!visible) {
    // 菜单关闭后检查鼠标是否还在当前消息项内
    setTimeout(() => {
      const messageEl = document.querySelectorAll(".message-item")[index];
      if (!messageEl?.matches(":hover")) {
        hoverIndex.value = -1;
      }
    }, 100);
  }
};
</script>

<style lang='scss' scoped>
.assistant-aside {
  width: 280px;
  height: 100%;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  background: #fff;
  padding: 20px 16px;
  overflow: hidden;
  .assistant-list {
    flex: 1;
    overflow-y: auto;
  }
  .assistant-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px;
    margin: 0 4px 10px;
    border-radius: 8px;
    border: 1px solid #eee;
    transition: background-color 0.3s;
    position: relative;
    overflow: hidden;

    &:hover {
      background-color: var(--el-fill-color);
      box-shadow: 2px 2px 2px 2px var(--el-fill-color);
    }
    &.active {
      background-color: rgba(0, 0, 0, 0.06);
    }

    .assistant-info {
      flex: 1;
      margin-right: 16px;
      display: flex;
      align-items: center;
      overflow: hidden;

      .name-desc {
        flex: 1;
        display: flex;
        flex-direction: column;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.88);
        margin-left: 10px;

        .name {
          font-weight: 700;
          margin-bottom: 6px;
        }
      }
    }

    .more-actions {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      cursor: pointer;
      color: var(--el-text-color-placeholder);
      transition: color 0.3s;
      &:hover {
        color: var(--el-color-primary);
      }
    }
  }
}
</style>